<template>
  <!--  不良代码-->
  <div class="content">
    <!-- 检索条件 -->
    <div class="pageSearchView">
      <el-form :inline="true" :model="searchParam" class="demo-form-inline">
        <el-form-item label="编码">
          <el-input v-model="searchParam.code" placeholder="请输入编码" clearable style="width: 200px" />
        </el-form-item>
        <el-form-item label="类型">
          <el-select v-model="searchParam.type" placeholder="请选择" style="width: 200px;">
            <el-option label="工废" :value="1" />
            <el-option label="料费" :value="2" />
            <el-option label="不合格" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="getList()">查询</el-button>
          <el-button :icon="Refresh" @click="resetSearch()">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="pageTableView">
      <div class="pageTableMenuView">
        <div class="pageTableTitle">列表信息 </div>
        <div class="pageTableButView">
          <el-button :icon="Plus" @click="handleAdd()">新建</el-button>
        </div>
      </div>
      <!-- 表格 -->
      <el-table class="pageTableClass" :data="paginatedData" border height="calc(100vh - 320px)">
        <el-table-column label="序号" align="center" width="70">
          <template #default="scope">
            <!-- 下标 + 1，计算公式：当前页数 * 每页大小 + 当前行的索引 + 1 --> {{ (pageSearch.current - 1) * pageSearch.pageSize +
              scope.$index + 1 }} </template>
        </el-table-column>
        <el-table-column prop="code" label="编码" align="center" min-width="200" />
        <el-table-column prop="description" label="描述" align="center" min-width="200" />
        <el-table-column prop="type" label="类型" width="120" :formatter="formatType" align="center" />
        <el-table-column prop="activate" label="是否启用" width="120" align="center" :formatter="formatIsActive" />
        <el-table-column prop="isCommonlyUsed" label="是否常用" width="120" align="center"
          :formatter="formatIsCommonlyUsed" />
        <el-table-column prop="remark" label="备注" align="center" min-width="200" />
        <el-table-column label="操作" align="center" fixed="right" width="180">
          <template #default="scope">
            <el-button @click="handleEdit(scope.row)" :disabled="scope.row.statusShow" size="small" type="text"
              :icon="Edit"> 编辑 </el-button>
            <el-button @click="handleDel(scope.row)" type="danger" size="small" plain text :icon="Delete">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagePagination">
        <el-pagination background v-model:current-page="pageSearch.current" v-model:page-size="pageSearch.pageSize"
          :page-sizes="[10, 20, 50, 100, 200, 500]" layout="total, sizes, prev, pager, next" :total="pageTotal"
          @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </div>
    <!-- 弹窗 -->
    <el-dialog v-model="showCrud" :title="crudTitle">
      <el-form :model="formData" label-width="90px" ref="ruleFormRef" :rules="rules" class="demo-ruleForm">
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="编码" prop="code" required>
              <el-input v-model="formData.code" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="描述" prop="description" required>
              <el-input v-model="formData.description" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="类型" prop="type" required>
              <el-select v-model="formData.type" placeholder="请选择">
                <el-option label="工废" :value="1" />
                <el-option label="料费" :value="2" />
                <el-option label="不合格" :value="3" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否启用" prop="activate">
              <el-select v-model="formData.activate" placeholder="请选择">
                <el-option label="否" :value="false" />
                <el-option label="启用" :value="true" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否常用" prop="isCommonlyUsed">
              <el-select v-model="formData.isCommonlyUsed" placeholder="请选择">
                <el-option label="否" :value="false" />
                <el-option label="是" :value="true" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="formData.remark" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template v-slot:footer>
        <div class="dialog-footer">
          <el-button @click="showCrud = false">取消</el-button>
          <el-button type="primary" @click="handleSave(ruleFormRef)">保存</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import { ref, reactive, computed, watch } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useEquipmentData } from '@/hooks/baseData/equipment';
import axiosInstance from '@/utils/http/api';
import { Delete, Edit, Search, Share, Upload, Refresh, Plus, DocumentCopy } from '@element-plus/icons-vue'

onMounted(() => {
  getList()
  getMaterial()
  getQualityPlanList()
})

const qualityPlanList = ref({})

const getQualityPlanList = () => {
  axiosInstance.post('/api/basedataQualityScheme/getAll', {})
    .then(res => {
      if (res.code !== 200) {
        ElMessage.error(res.message);
        return false
      }
      qualityPlanList.value = res.data
    });
}


const pageSearch = ref({
  current: 1,
  pageSize: 10
})

const rowInfo = ref({})

const materialList = ref({})

const getMaterial = () => {
  axiosInstance.post('/api/basedataMaterial/getAll', {})
    .then(res => {
      materialList.value = res.data
    })
}

// 物料删除
const handleMaterialDelete = (e, i) => {
  ElMessageBox.confirm(
    '确认删除该条物料？',
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      const jsonParam = JSON.parse(rowInfo.value.qualityJson);
      jsonParam.materialTable.splice(i, 1);
      rowInfo.value.qualityJson = JSON.stringify(jsonParam);
    })

};



const formatIsActive = (row, column, cellValue) => {
  return cellValue === true ? '启用' : '-';
}
const formatIsCommonlyUsed = (row, column, cellValue) => {
  return cellValue === true ? '是' : '-';
}
const formatType = (row, column, cellValue) => {
  const typeMap = {
    '1': '工废',
    '2': '料费',
    '3': '不合格'
  };
  return typeMap[cellValue] || '';
}
const pageTotal = ref(null)//页面总数
const isEdit = ref(false); // 是否编辑
const showCrud = ref(false); // 编辑/新建弹框
const searchParam = ref({})//页面检索条件
const crudTitle = computed(() => {
  return isEdit.value ? '编辑' : '新建';
});//弹出层标题
import type { ComponentSize, FormInstance, FormRules } from 'element-plus'

// 质检方式
const qualityWayList = reactive([
  {
    label: '全检',
    value: '1'
  }, {
    label: '比例抽检',
    value: '2'
  }, {
    label: '固定抽检',
    value: '3'
  }, {
    label: '自定义抽检',
    value: '4'
  }
])


// 判断质检类型
const getQualityTypeByValue = (e) => {
  let name = null
  for (const item of qualityTypeList) {
    if (e == item.value) {
      name = item.label
    }
  }
  return name
}

// 质检类型
const qualityTypeList = reactive([
  {
    label: '首件检',
    value: '1',
    type: 'material'
  },
  {
    label: '末件检',
    value: '2',
    type: 'material'
  },
  {
    label: '生产',
    value: '3',
    type: 'material'
  },
  {
    label: '巡检',
    value: '4',
    type: 'material'
  },
  {
    label: '入库检',
    value: '5',
    type: 'procedure'
  },
  {
    label: '出库检',
    value: '6',
    type: 'procedure'
  },
  {
    label: '来料检',
    value: '7',
    type: 'procedure'
  },
]);

const ruleFormRef = ref<FormInstance>()

// 修改 formData 的定义和初始化
const formData = ref({
  code: '',
  description: '',
  type: null,
  activate: true,
  isCommonlyUsed: true,
  remark: ''
})

// 修改 rules 验证规则
const rules = reactive<FormRules<typeof formData.value>>({
  code: [
    { required: true, message: '编码不可以为空', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '描述不可以为空', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '类型不可以为空', trigger: 'change' }
  ],
  activate: [
    { required: true, message: '是否启用不可以为空', trigger: 'change' }
  ],
  isCommonlyUsed: [
    { required: true, message: '是否常用不可以为空', trigger: 'change' }
  ]
})

const paginatedData = ref([]);

// 获取列表接口
const getList = () => {
  axiosInstance.post('/api/qualityBadCode/getPage', {
    ...searchParam.value,
    ...pageSearch.value
  })
    .then(res => {
      if (res.code !== 200) {
        ElMessage.error(res.message);
        return false
      }
      paginatedData.value = res.data.records
      pageTotal.value = res.data.total
    });
}

const handleSizeChange = (e) => {
  pageSearch.value.pageSize = e
  getList()
}

const handleCurrentChange = (e) => {
  pageSearch.value.current = e
  getList()
}

// 重置搜索条件
const resetSearch = () => {
  searchParam.value = {};
  pageSearch.value.current = 1
  getList();
};

// 点击新建 - 修正初始化方式
const handleAdd = () => {
  isEdit.value = false;
  // 直接重置表单数据，而不是创建新的 ref
  formData.value = {
    code: '',
    description: '',
    type: null,
    activate: true,
    isCommonlyUsed: true,
    remark: ''
  }
  showCrud.value = true;
  ruleFormRef.value?.resetFields();
};

// 点击编辑
const handleEdit = (row: any) => {
  isEdit.value = true;
  formData.value = { ...{}, ...row }
  showCrud.value = true;
};

// 删除记录
const handleDel = (row: any) => {
  ElMessageBox.confirm('确定删除该条记录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    axiosInstance.delete(`/api/qualityBadCode/delete`, {
      data: {
        ids: [row.id]
      }
    }).then(res => {
      ElMessage.success('删除成功');
      getList(); // 刷新数据
    });


  })
};


// 弹框确定 确认新建 确定编辑
const handleSave = async (e: FormInstance | undefined) => {
  if (!e) return
  await e.validate((valid, fields) => {
    if (valid) {
      const jsonString = JSON.stringify(formData.value);
      formData.value.qualityJson = jsonString;
      if (isEdit.value) {
        // 编辑
        axiosInstance.put('/api/qualityBadCode/update', formData.value).then(res => {
          if (res.code != 200) {
            ElMessage.error(res.message)
            return false
          }
          ElMessage.success('操作成功!')
          showCrud.value = false;
          getList(); // 刷新数据
        })
      } else {
        // 新建
        const paramData = formData.value
        paramData.id = null
        paramData.status = false
        axiosInstance.post('/api/qualityBadCode/save', paramData).then(res => {
          if (res.code != 200) {
            ElMessage.error(res.message)
            return false
          }
          ElMessage.success('操作成功!')
          showCrud.value = false;
          getList(); // 刷新数据
        })
      }

    }
  })
}

</script>
<style scoped></style>
